﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using ImageConverter.Utils;

namespace ImageConverter.Data.Containers
{
    public class FileSystemReader : IEntryReader
    {
        #region IEntryReader Members

        public event OnEntryReadHandler OnEntryRead;

        public event OnEntryReadErrorHandler OnEntryReadError;

        public bool ValidateEntries(string fileName)
        {
            return Directory.Exists(fileName);
        }

        public ContainerResult ExtractEntries(string fileName, CancellationToken cancellationToken, PauseToken pauseToken)
        {
            ContainerResult result = new ContainerResult();

            DirectoryInfo dir = new DirectoryInfo(fileName);
            if (!dir.Exists)
            {
                result.IsCompleted = false;
                result.ErrorValue = new DirectoryNotFoundException(fileName);
                result.IsError = true;
            }
            else
            {
                foreach (var f in dir.GetFiles())
                {
                    while (pauseToken.IsPaused && !cancellationToken.IsCancellationRequested)
                    {
                        Thread.Sleep(200);
                    }

                    if (cancellationToken.IsCancellationRequested)
                    {
                        return new ContainerResult()
                        {
                            IsCompleted = true
                        };
                    }

                    byte[] data = null;
                    try
                    {
                        data = File.ReadAllBytes(f.FullName);

                        if (OnEntryRead != null)
                            OnEntryRead(new EntryData()
                            {
                                ByteData = data,
                                FileName = f.Name
                            });
                    }
                    catch (Exception ex)
                    {
                        OnEntryReadError(f.Name, ex);
                    }
                }

                result.IsCompleted = true;
            }

            return result;
        }

        public IEnumerable<string> GetArchiveEntries(string fileName)
        {
            if (!Directory.Exists(fileName))
                return new string[] { };

            return Directory.GetFiles(fileName).Select( fName => Path.GetFileName(fName));
        }

        #endregion
    }
}
